<template>
  <div class="activity-component">
    <el-card class="activity-card" :class="{ 'edit-mode': isEditMode }">
      <!-- 编辑模式工具栏 -->
      <div v-if="isEditMode" class="component-toolbar">
        <el-button-group size="small">
          <el-button @click="$emit('configure-component', componentConfig)" icon="Setting" circle />
          <el-button @click="$emit('toggle-visibility')" :icon="component.visible ? 'View' : 'Hide'" circle />
          <el-button @click="$emit('remove')" icon="Delete" type="danger" circle />
        </el-button-group>
      </div>

      <!-- 组件标题 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ component.title }}</span>
          <div class="header-actions">
            <el-button-group size="small">
              <el-button 
                v-for="tab in activityTabs" 
                :key="tab.key"
                :type="currentTab === tab.key ? 'primary' : ''"
                @click="currentTab = tab.key"
                size="small"
              >
                {{ tab.label }}
              </el-button>
            </el-button-group>
            <el-dropdown @command="handleCommand">
              <el-button size="small" icon="More" circle />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                  <el-dropdown-item command="filter">筛选</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="settings" divided>设置</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 活动筛选 -->
      <div class="activity-filters" v-if="showFilters">
        <el-select v-model="typeFilter" placeholder="活动类型" size="small" style="width: 120px;">
          <el-option label="全部" value="" />
          <el-option label="订单" value="order" />
          <el-option label="用户" value="user" />
          <el-option label="系统" value="system" />
          <el-option label="财务" value="finance" />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          style="margin-left: 8px;"
        />
      </div>

      <!-- 活动列表 -->
      <div class="activity-list">
        <el-timeline>
          <el-timeline-item
            v-for="activity in filteredActivities"
            :key="activity.id"
            :timestamp="formatTimestamp(activity.timestamp)"
            :type="getActivityType(activity.type)"
            :icon="getActivityIcon(activity.type)"
            placement="top"
          >
            <div class="activity-item" :class="activity.type">
              <div class="activity-header">
                <div class="activity-title">
                  {{ activity.title }}
                </div>
                <div class="activity-meta">
                  <el-tag :type="getActivityTagType(activity.type)" size="small">
                    {{ getActivityTypeText(activity.type) }}
                  </el-tag>
                  <span class="activity-user" v-if="activity.user">
                    <el-icon><User /></el-icon>
                    {{ activity.user }}
                  </span>
                </div>
              </div>
              
              <div class="activity-content">
                <p class="activity-description">{{ activity.description }}</p>
                
                <!-- 订单相关信息 -->
                <div v-if="activity.type === 'order' && activity.data" class="activity-data">
                  <div class="data-item">
                    <span class="data-label">订单号:</span>
                    <span class="data-value">{{ activity.data.orderNo }}</span>
                  </div>
                  <div class="data-item" v-if="activity.data.amount">
                    <span class="data-label">金额:</span>
                    <span class="data-value amount">¥{{ activity.data.amount }}</span>
                  </div>
                  <div class="data-item" v-if="activity.data.customer">
                    <span class="data-label">客户:</span>
                    <span class="data-value">{{ activity.data.customer }}</span>
                  </div>
                </div>
                
                <!-- 用户相关信息 -->
                <div v-if="activity.type === 'user' && activity.data" class="activity-data">
                  <div class="data-item" v-if="activity.data.role">
                    <span class="data-label">角色:</span>
                    <span class="data-value">{{ activity.data.role }}</span>
                  </div>
                  <div class="data-item" v-if="activity.data.department">
                    <span class="data-label">部门:</span>
                    <span class="data-value">{{ activity.data.department }}</span>
                  </div>
                </div>
                
                <!-- 系统相关信息 -->
                <div v-if="activity.type === 'system' && activity.data" class="activity-data">
                  <div class="data-item" v-if="activity.data.module">
                    <span class="data-label">模块:</span>
                    <span class="data-value">{{ activity.data.module }}</span>
                  </div>
                  <div class="data-item" v-if="activity.data.version">
                    <span class="data-label">版本:</span>
                    <span class="data-value">{{ activity.data.version }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="activity-actions" v-if="activity.actions">
                <el-button
                  v-for="action in activity.actions"
                  :key="action.key"
                  :type="action.type || 'text'"
                  size="small"
                  @click="handleActivityAction(activity, action)"
                >
                  {{ action.label }}
                </el-button>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
        
        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore">
          <el-button @click="loadMore" :loading="loading" type="text">
            {{ loading ? '加载中...' : '加载更多' }}
          </el-button>
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredActivities.length === 0" class="empty-state">
          <el-empty description="暂无活动记录" :image-size="80" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { 
  User, 
  ShoppingCart, 
  UserFilled, 
  Setting, 
  Bell, 
  Wallet,
  More,
  View,
  Hide,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  componentId: {
    type: String,
    required: true
  },
  componentConfig: {
    type: Object,
    default: () => ({})
  },
  isEditMode: {
    type: Boolean,
    default: false
  },
  visible: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['toggle-visibility', 'remove-component', 'configure-component'])

// 响应式数据
const currentTab = ref('all')
const showFilters = ref(false)
const typeFilter = ref('')
const dateRange = ref([])
const loading = ref(false)
const hasMore = ref(true)

// 活动标签页
const activityTabs = [
  { key: 'all', label: '全部' },
  { key: 'recent', label: '最近' },
  { key: 'important', label: '重要' }
]

// 模拟活动数据
const activities = ref([
  {
    id: 1,
    type: 'order',
    title: '新订单创建',
    description: '客户张三创建了一个新的销售订单',
    user: '张三',
    timestamp: '2024-01-24 14:30:00',
    important: true,
    data: {
      orderNo: 'SO202401240001',
      amount: '15,680.00',
      customer: '北京科技有限公司'
    },
    actions: [
      { key: 'view', label: '查看', type: 'primary' },
      { key: 'process', label: '处理', type: 'success' }
    ]
  },
  {
    id: 2,
    type: 'user',
    title: '新用户注册',
    description: '新员工李四完成了系统注册',
    user: '系统管理员',
    timestamp: '2024-01-24 13:45:00',
    important: false,
    data: {
      role: '销售员',
      department: '销售部'
    },
    actions: [
      { key: 'approve', label: '审批', type: 'warning' }
    ]
  },
  {
    id: 3,
    type: 'finance',
    title: '付款确认',
    description: '订单SO202401230005的付款已确认到账',
    user: '财务部',
    timestamp: '2024-01-24 12:20:00',
    important: true,
    data: {
      orderNo: 'SO202401230005',
      amount: '28,900.00',
      paymentMethod: '银行转账'
    },
    actions: [
      { key: 'view', label: '查看凭证', type: 'primary' }
    ]
  },
  {
    id: 4,
    type: 'system',
    title: '系统更新',
    description: '库存管理模块已更新到最新版本',
    user: '系统',
    timestamp: '2024-01-24 11:00:00',
    important: false,
    data: {
      module: '库存管理',
      version: 'v2.1.3'
    }
  },
  {
    id: 5,
    type: 'order',
    title: '订单状态变更',
    description: '订单SO202401230003已发货',
    user: '仓库管理员',
    timestamp: '2024-01-24 10:15:00',
    important: false,
    data: {
      orderNo: 'SO202401230003',
      status: '已发货',
      trackingNo: 'SF1234567890'
    },
    actions: [
      { key: 'track', label: '物流跟踪', type: 'info' }
    ]
  },
  {
    id: 6,
    type: 'user',
    title: '权限变更',
    description: '用户王五的权限已更新',
    user: '系统管理员',
    timestamp: '2024-01-24 09:30:00',
    important: false,
    data: {
      role: '部门经理',
      department: '采购部'
    }
  },
  {
    id: 7,
    type: 'finance',
    title: '月度报表生成',
    description: '2024年1月财务报表已自动生成',
    user: '系统',
    timestamp: '2024-01-24 08:00:00',
    important: true,
    actions: [
      { key: 'download', label: '下载', type: 'success' }
    ]
  },
  {
    id: 8,
    type: 'system',
    title: '数据备份完成',
    description: '每日数据备份任务已成功完成',
    user: '系统',
    timestamp: '2024-01-24 02:00:00',
    important: false,
    data: {
      backupSize: '2.3GB',
      duration: '15分钟'
    }
  }
])

// 计算属性
const filteredActivities = computed(() => {
  let filtered = activities.value
  
  // 按标签页筛选
  if (currentTab.value === 'recent') {
    const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000)
    filtered = filtered.filter(activity => new Date(activity.timestamp) > oneDayAgo)
  } else if (currentTab.value === 'important') {
    filtered = filtered.filter(activity => activity.important)
  }
  
  // 按类型筛选
  if (typeFilter.value) {
    filtered = filtered.filter(activity => activity.type === typeFilter.value)
  }
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    filtered = filtered.filter(activity => {
      const activityDate = new Date(activity.timestamp)
      return activityDate >= startDate && activityDate <= endDate
    })
  }
  
  return filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
})

// 方法
const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffTime = now - date
  const diffMinutes = Math.floor(diffTime / (1000 * 60))
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffMinutes < 1) return '刚刚'
  if (diffMinutes < 60) return `${diffMinutes}分钟前`
  if (diffHours < 24) return `${diffHours}小时前`
  if (diffDays < 7) return `${diffDays}天前`
  
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getActivityType = (type) => {
  const types = {
    order: 'primary',
    user: 'success',
    system: 'info',
    finance: 'warning'
  }
  return types[type] || 'info'
}

const getActivityIcon = (type) => {
  const icons = {
    order: ShoppingCart,
    user: UserFilled,
    system: Setting,
    finance: Wallet
  }
  return icons[type] || Bell
}

const getActivityTagType = (type) => {
  const types = {
    order: 'primary',
    user: 'success',
    system: 'info',
    finance: 'warning'
  }
  return types[type] || 'info'
}

const getActivityTypeText = (type) => {
  const texts = {
    order: '订单',
    user: '用户',
    system: '系统',
    finance: '财务'
  }
  return texts[type] || '其他'
}

const handleCommand = (command) => {
  switch (command) {
    case 'refresh':
      refreshActivities()
      break
    case 'filter':
      showFilters.value = !showFilters.value
      break
    case 'export':
      ElMessage.info('导出功能开发中...')
      break
    case 'settings':
      ElMessage.info('设置功能开发中...')
      break
  }
}

const refreshActivities = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('活动记录已刷新')
  }, 1000)
}

const loadMore = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    hasMore.value = false
    ElMessage.info('没有更多数据了')
  }, 1000)
}

const handleActivityAction = (activity, action) => {
  switch (action.key) {
    case 'view':
      ElMessage.info(`查看${activity.type === 'order' ? '订单' : '详情'}: ${activity.data?.orderNo || activity.title}`)
      break
    case 'process':
      ElMessage.info(`处理订单: ${activity.data?.orderNo}`)
      break
    case 'approve':
      ElMessage.info('审批功能开发中...')
      break
    case 'track':
      ElMessage.info(`物流跟踪: ${activity.data?.trackingNo}`)
      break
    case 'download':
      ElMessage.info('下载报表功能开发中...')
      break
    default:
      ElMessage.info('功能开发中...')
  }
}
</script>

<style scoped>
.activity-component {
  position: relative;
}

.activity-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.activity-card.edit-mode {
  border: 2px dashed #409eff;
  position: relative;
}

.activity-card.edit-mode:hover {
  border-color: #67c23a;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.component-toolbar {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  padding: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-filters {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  flex-wrap: wrap;
  gap: 8px;
}

.activity-list {
  max-height: 500px;
  overflow-y: auto;
}

.activity-item {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.activity-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.activity-item.order {
  border-left: 4px solid #409eff;
}

.activity-item.user {
  border-left: 4px solid #67c23a;
}

.activity-item.system {
  border-left: 4px solid #909399;
}

.activity-item.finance {
  border-left: 4px solid #e6a23c;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 8px;
}

.activity-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.activity-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.activity-user {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.activity-content {
  margin-bottom: 12px;
}

.activity-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  margin: 0 0 8px 0;
}

.activity-data {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-top: 8px;
}

.data-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.data-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.data-value {
  font-size: 12px;
  color: #303133;
  font-weight: 600;
}

.data-value.amount {
  color: #f56c6c;
}

.activity-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.load-more {
  text-align: center;
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 20px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .activity-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .activity-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .activity-data {
    flex-direction: column;
    gap: 8px;
  }
  
  .activity-actions {
    justify-content: flex-start;
  }
}
</style>